package com.meituan.catering.management.order.biz.service.impl;

import com.meituan.catering.management.common.model.api.http.UserContextHttpRequest;
import com.meituan.catering.management.common.model.biz.PageBO;
import com.meituan.catering.management.order.api.http.model.request.SearchCateringOrderHttpRequest;
import com.meituan.catering.management.order.biz.model.CateringOrderBO;
import com.meituan.catering.management.order.biz.model.CateringOrderItemAccessoryBO;
import com.meituan.catering.management.order.biz.model.CateringOrderItemBO;
import com.meituan.catering.management.order.biz.model.converter.CateringOrderBOConverter;
import com.meituan.catering.management.order.biz.service.CateringOrderQueryService;
import com.meituan.catering.management.order.dao.mapper.CateringOrderItemAccessoryMapper;
import com.meituan.catering.management.order.dao.mapper.CateringOrderItemMapper;
import com.meituan.catering.management.order.dao.mapper.CateringOrderMapper;
import com.meituan.catering.management.order.dao.model.CateringOrderDO;
import com.meituan.catering.management.order.dao.model.CateringOrderItemAccessoryDO;
import com.meituan.catering.management.order.dao.model.CateringOrderItemDO;
import com.meituan.catering.management.order.dao.model.request.SearchCateringOrderDataRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单查询 服务接口
 */
@Service
public class CateringOrderQueryServiceImpl implements CateringOrderQueryService {
    @Resource
    CateringOrderMapper cateringOrderMapper;
    @Resource
    CateringOrderItemMapper cateringOrderItemMapper;
    @Resource
    CateringOrderItemAccessoryMapper cateringOrderItemAccessoryMapper;


    @Override
    public PageBO searchForPage(UserContextHttpRequest userContextHttpRequest, SearchCateringOrderHttpRequest request) {
        /*
         * 构建订单 DO请求体
         */
        SearchCateringOrderDataRequest searchCateringOrderDataRequest = buildSearchOrderRequest(userContextHttpRequest, request);
        /*
         * 查询满足条件的总数量
         */
        Integer count=cateringOrderMapper.countForPage(searchCateringOrderDataRequest);
        PageBO<CateringOrderBO> pageBO;
        pageBO=buildPageBO(request,count);
        List<CateringOrderDO> cateringOrderDOS;
        if(count>0){
            cateringOrderDOS=cateringOrderMapper.searchForPage(searchCateringOrderDataRequest);
            if(cateringOrderDOS!=null)
            {
                pageBO.getRecords().addAll(cateringOrderDOS.stream().map(CateringOrderBOConverter::fromDO).collect(Collectors.toList()));
            }
        }
        return pageBO;
    }

    /**
     * @param userContextHttpRequest 头部信息(租户号，用户号)
     * @param orderId 订单id
     * @return CateringOrderBO
     */
    @Override
    public CateringOrderBO findById(UserContextHttpRequest userContextHttpRequest, Long orderId) {
        /*
         * 根据租户号 和订单id查询订单详情
         */
        CateringOrderDO cateringOrderDO=cateringOrderMapper.findById(userContextHttpRequest.getTenantId(),orderId);
        if (cateringOrderDO!=null)
        {
            /*
             * 订单本身转BO
             */
            CateringOrderBO cateringOrderBO = CateringOrderBOConverter.fromDO(cateringOrderDO);
            /*
             * 根据订单id查询出子项列表
             */
            List<CateringOrderItemDO> cateringOrderItemDOS=cateringOrderItemMapper.findItemsByOrederId(userContextHttpRequest.getTenantId(),orderId);
            List<CateringOrderItemBO> cateringOrderItemBOS=new ArrayList<>();
            /*
             * 根据查询到的子列表集合 遍历其id查询加料表
             */
            for (CateringOrderItemDO item:cateringOrderItemDOS) {
                List<CateringOrderItemAccessoryDO> cateringOrderItemAccessoryDOS=cateringOrderItemAccessoryMapper.findItemAccessorysByItemId(item.getId(),item.getTenantId());
                /*
                 * 订单子项本身转BO
                 */
                CateringOrderItemBO cateringOrderItemBO = CateringOrderBOConverter.fromOrederItemDO(item);
                /*
                 * 订单子项加料转换BO
                 */
                cateringOrderItemBO.getAcc().addAll(cateringOrderItemAccessoryDOS.stream().map(CateringOrderBOConverter::fromItemAccessoryDO).collect(Collectors.toList()));
                cateringOrderItemBOS.add(cateringOrderItemBO);
            }
            cateringOrderBO.getCateringOrderItemBOList().addAll(cateringOrderItemBOS);
            return cateringOrderBO;
        }else {
            throw new IllegalArgumentException("订单id:"+orderId+"不存在");
        }

    }

    /**
     * @param orderId 订单号
     * @param seqNo 子订单序号
     * @param tenantId 租户号
     * @return CateringOrderItemBO
     */
    @Override
    public CateringOrderItemBO findItemByOrderId(Long orderId, String seqNo, Long tenantId) {
       CateringOrderItemDO itemDO=cateringOrderItemMapper.findItemByOrderId(orderId,seqNo,tenantId);
        List<CateringOrderItemAccessoryBO> itemAccsByItemId = this.findItemAccsByItemId(itemDO.getId(), tenantId);
        CateringOrderItemBO cateringOrderItemBO = CateringOrderBOConverter.fromOrederItemDO(itemDO);
        cateringOrderItemBO.setAcc(itemAccsByItemId);
        return cateringOrderItemBO;
    }

    /**
     *  查找单个加料
     * @param itemId 订单子项id
     * @param seqNo 序号
     * @param tenantId 租户号
     * @return CateringOrderItemAccessoryBO
     */
    @Override
    public CateringOrderItemAccessoryBO findItemAccByItemId(Long itemId, String seqNo, Long tenantId) {
        CateringOrderItemAccessoryDO itemAccessoryByItemId = cateringOrderItemAccessoryMapper.findItemAccessoryByItemId(itemId, seqNo, tenantId);
        return CateringOrderBOConverter.fromItemAccessoryDO(itemAccessoryByItemId);
    }
    /**
     *  查找加料集合
     * @param itemId 订单子项id
     * @param tenantId 租户号
     * @return List<CateringOrderItemAccessoryBO>
     */
    @Override
    public List<CateringOrderItemAccessoryBO> findItemAccsByItemId(Long itemId, Long tenantId) {
        List<CateringOrderItemAccessoryDO> itemAccessoryByItemId = cateringOrderItemAccessoryMapper.findItemAccessorysByItemId(itemId, tenantId);
       if (itemAccessoryByItemId.size()>0)
       {
           return itemAccessoryByItemId.stream().map(CateringOrderBOConverter::fromItemAccessoryDO).collect(Collectors.toList());
       }
       return null;
    }


    @Override
    public List<CateringOrderItemBO> findItemsByOrderId(Long tenantId, Long orderId) {
        List<CateringOrderItemDO> itemsByOrederId = cateringOrderItemMapper.findItemsByOrederId(tenantId, orderId);
        List<CateringOrderItemBO> cateringOrderItemBOS=new ArrayList<>();
        cateringOrderItemBOS.addAll(itemsByOrederId.stream().map(CateringOrderBOConverter::fromOrederItemDO).collect(Collectors.toList()));
        return cateringOrderItemBOS;
    }


    private PageBO<CateringOrderBO> buildPageBO(SearchCateringOrderHttpRequest request, int totalCount) {
        PageBO<CateringOrderBO> cateringOrderBOPageBO = new PageBO();
        cateringOrderBOPageBO.setTotalCount(totalCount);
        cateringOrderBOPageBO.setPageSize(request.getPageSize());
        cateringOrderBOPageBO.setTotalPageCount(totalCount / request.getPageSize() + (totalCount % request.getPageSize() == 0 ? 0 : 1));
        if (request.getPageIndex() > cateringOrderBOPageBO.getTotalPageCount()) {
            cateringOrderBOPageBO.setPageIndex(cateringOrderBOPageBO.getTotalPageCount());
        } else {
            cateringOrderBOPageBO.setPageIndex(request.getPageIndex());
        }
        return cateringOrderBOPageBO;
    }

    private static SearchCateringOrderDataRequest buildSearchOrderRequest(UserContextHttpRequest userContextHttpRequest,SearchCateringOrderHttpRequest request){
        SearchCateringOrderDataRequest searchRequest=new SearchCateringOrderDataRequest();
        searchRequest.setTenantId(userContextHttpRequest.getTenantId());
        searchRequest.setMaxPrice(request.getCondition().getTotalPrice().getTo());
        searchRequest.setMinPrice(request.getCondition().getTotalPrice().getFrom());
        searchRequest.setSkip((request.getPageIndex()-1) * request.getPageSize());
        searchRequest.setSize(request.getPageSize());
        /*
         * 转换状态枚举 名
         */
        if (request.getCondition().getStatus()!=null)
        {
            searchRequest.setStatus(String.valueOf(request.getCondition().getStatus()));
        }
        searchRequest.setTableNo(request.getCondition().getTableNo());
        searchRequest.setCustomerCount(request.getCondition().getCustomerCount());
        /*
         * 转换 排序规则
         */
        List<String> sortStr=new ArrayList<>();
        for (SearchCateringOrderHttpRequest.SortField sortField:request.getSortFields()) {
            /*
             * 拼接排序规则
             */
            sortStr.add(sortField.getField()+" "+(sortField.getAsc()?"ASC":"DESC"));
        }
        searchRequest.setSortFields(sortStr);

        return searchRequest;
    }
}
